package com.example.demo.controller;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class ShiroController {
    @RequestMapping({"/index",""})
    public String toindex(Model model){
        model.addAttribute("msg","shiro");
        return "index.html";

    }
    @RequestMapping("/user/add")
    public String toadd(){
        return "AddUser.html";
    }
    @RequestMapping("/user/update")
    public String toupdate(){
        return "UpdateUser.html";
    }
    @RequestMapping("/tologin")
    public String tologin(){
        return "login.html";
    }
    @RequestMapping("/login")
    public String login(String username,String password,Model model){
        //获取当前用户
        Subject subject= SecurityUtils.getSubject();
        //封装用户的token
        UsernamePasswordToken token=new UsernamePasswordToken(username,password);

        try {
            subject.login(token);//执行登录方法无异常就行了
            return "main.html";
        }catch (UnknownAccountException e){
            model.addAttribute("msg","用户名不存在");
            return "login.html";
        }catch (IncorrectCredentialsException e){
            model.addAttribute("msg","用户名或者密码错误!");
            return "login.html";
        }
    }

    @RequestMapping("/401")
    @ResponseBody
    public String noauth(){
        return "未授权不得访问!";
    }
}
